package com.CampaignManager.server;

import java.io.IOException;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.mail.Address;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class MailHandlerServlet extends HttpServlet {  
	
    @SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    	
    	PersistenceManager pm = CampaignServiceImpl.PMF.getPersistenceManager();
    	Logger LOG = Logger.getLogger(MailHandlerServlet.class.getName());
    	
    	Properties props = new Properties();
    	Session session = Session.getDefaultInstance(props, null);
    	try {
			MimeMessage message = new MimeMessage(session, req.getInputStream());
			
			Query q = pm.newQuery(Player.class);
			List<Player> players = (List<Player>) q.execute();
			for (Player player : players) {

				LOG.log(Level.INFO, "getMessageID: "+message.getMessageID());
				LOG.log(Level.INFO, "message.getSubject: "+message.getSubject());
				
				for (Address a : message.getFrom()) {
					
					LOG.log(Level.INFO, "Email from: "+a.toString());
					
					if (a.toString().toLowerCase().contains(player.getEmail().toLowerCase()	)) {
						
						LOG.log(Level.INFO, a.toString()+" DOES contain "+player.getEmail());
						
						Query j = pm.newQuery(Job.class);
						j.setFilter("email == e");
			    		j.declareParameters("String e");
			    		List<Job> jobs = (List<Job>) j.execute(player.getEmail());
			    		for (Job job : jobs) {
			    			if (job.getStatus().equals("Pending")) {
			    				job.setStatus("Incomplete");
			    				if (message.getMessageID() != null)
			    					job.setStoryMessageID(message.getMessageID().replace("<", "").replace(">", ""));
			    				job.setStorySubject(message.getSubject());
			    			}
			    		}					
					} else {
						LOG.log(Level.INFO, a.toString()+" does not contain "+player.getEmail());
					}
				}
			}	
		} catch (MessagingException e) {
			e.printStackTrace();
			throw new IOException(e.getMessage(),e);
		} finally {
    		pm.close();
		}
    }
}
